import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/view/home.vue'
import Login from '@/view/login.vue'
import User from '@/view/user.vue'
import Role from '@/view/role.vue'
import Goods from '@/view/goods.vue'
import addGoods from '@/view/addGoods.vue'
import brand from '@/view/brand.vue'
import order from '@/view/order.vue'
import ShopIndex from '@/view/shop/index.vue'
import shopLogin from '@/view/shop/login.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/shoplogin', component: shopLogin },
  { path: '/login', component: Login },
  { path: '/userInfo', component: () => import('@/view/shop/userInfo.vue') },
  { path: '/index', component: ShopIndex },
  { path: '/shopregister', component: () => import('@/view/shop/register.vue') },
  { path: '/shopcart', component: () => import('@/view/shop/shopcart.vue') },
  { path: '/settlement', component: () => import('@/view/shop/settlement.vue') },
  { path: '/userOrder', component: () => import('@/view/shop/userOrder.vue') },
  {
    path: '/goodDetail', component: () => import('@/view/shop/goodDetail.vue')
  },
  {
    path: '/home',
    component: Home,
    redirect: '/adminIndex',
    children: [
      { path: '/user', component: User },
      { path: '/role', component: Role },
      {
        path: '/goods', component: Goods
      },
      {
        path: '/addGoods', component: addGoods
      },
      {
        path: '/brand', component: brand
      },
      {
        path: '/order', component: order
      },
      {
        path: '/shopList', component: () => import('@/view/shops.vue')
      },
      {
        path: '/adminIndex', component: () => import('@/view/adminIndex.vue')
      }

    ]
  },
  { path: '/login', component: Login }

]

const router = new VueRouter({
  routes
})
router.beforeEach(function (to, from, next) {
  // 1.拿到用户将要访问的hash地址
  var path = to.path
  // 2.判断hash地址是否等于/home，如果等于则需要判断是否登录,不等于则直接放行
  if (path !== '/login' && path !== '/shoplogin') {
    // 3.如果访问的地址是/home，则需要读取localStorage中的值，有则放行，无则强制跳转
    const token = localStorage.getItem('Authorization')
    if (token) {
      next()
    } else {
      if (from.path === '/login') {
        next('/login')
      } else if (from.path === '/shoplogin') {
        next('/shoplogin')
      }
    }
  } else {
    next()
  }
})

export default router
